package com.zzstm.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzstm.commonUtils.CourseWebVOComment;
import com.zzstm.commonUtils.JwtUtils;
import com.zzstm.commonUtils.R;
import com.zzstm.eduservice.client.OrderClient;
import com.zzstm.eduservice.entity.EduCourse;
import com.zzstm.eduservice.entity.chapter.ChapterVO;
import com.zzstm.eduservice.entity.frontvo.CourseFrontVO;
import com.zzstm.eduservice.entity.frontvo.CourseWebVO;
import com.zzstm.eduservice.service.EduChapterService;
import com.zzstm.eduservice.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
@CrossOrigin
public class CourseFrontController {

    @Autowired
    private EduCourseService courseService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private OrderClient orderClient;

    //前台课程条件查询带分页
    @PostMapping("/getCourseFrontList/{pageNum}/{pageSize}")
    public R getCourseFrontList(@PathVariable long pageSize,
                    @PathVariable long pageNum,
                    @RequestBody(required = false) CourseFrontVO courseVO){
        Page<EduCourse> page = new Page<>(pageNum,pageSize);
        Map<String,Object> map = courseService.getCourseFrontList(page,courseVO);
        return R.ok().data(map);
    }

    //课程详情
    @GetMapping("/getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request) {
        //每次点击，viewCount数量+1，作为学习人数
        CourseWebVO courseWebVO = courseService.getBaseCourseInfo(courseId);
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseWebVO,eduCourse);
        eduCourse.setViewCount(eduCourse.getViewCount() + 1);
        courseService.updateById(eduCourse);

        List<ChapterVO> chapterVideoList = chapterService.getChapterVideoByCourseId(courseId);
        //根据课程id和用户id查询订单表订单状态
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        boolean isBuyCourse = false;
        if (!StringUtils.isEmpty(userId)) {
            isBuyCourse = orderClient.isBuyCourse(courseId, userId);
        }
        return R.ok().data("courseWebVO", courseWebVO).data("chapterVideoList", chapterVideoList).data("isBuyCourse", isBuyCourse);
    }

    @GetMapping("/getCourseInfoById/{courseId}")
    public CourseWebVOComment getCourseInfoById(@PathVariable String courseId){
        CourseWebVO courseInfo = courseService.getBaseCourseInfo(courseId);
        CourseWebVOComment comment = new CourseWebVOComment();
        BeanUtils.copyProperties(courseInfo,comment);
        return comment;
    }

}
